package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.PTReport;

public class PTReportPresenter extends AbstractPresenter<PTReport> {
	final String SINGLEITEM = "pTReport";
	final String MULTIITEM = "pTReports";
	
	public ArrayList<PTReport> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public PTReport tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public PTReport createItemFromJSONObject(JSONObject jsonObject){
		PTReport item = new PTReport();
		try{
			item.setMonth(jsonObject.getInt("month"));
			item.setQty(jsonObject.getInt("qty"));
			item.setYear(jsonObject.getInt("year"));
			
			if(!jsonObject.isNull("beer")){
				//create product if set
				final BeerViewPresenter presenter = new BeerViewPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("beer");
				item.setBeer(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setBeer(null);
			}
			
			if(!jsonObject.isNull("packageType")){
				//create product if set
				final PackageTypeViewPresenter presenter = new PackageTypeViewPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("packageType");
				item.setPackageType(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setPackageType(null);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(PTReport item){
		try{
			JSONObject json = new JSONObject();
			json.put("month", item.getMonth());
			json.put("qty", item.getQty());
			json.put("year", item.getYear());

			if(item.getBeer()!=null){
				final BeerViewPresenter presenter = new BeerViewPresenter();
				json.put("beer", presenter.createJSON(item.getBeer()));
			} else {
				json.put("beer", JSONObject.NULL);
			}

			if(item.getPackageType()!=null){
				final PackageTypeViewPresenter presenter = new PackageTypeViewPresenter();
				json.put("packageType", presenter.createJSON(item.getPackageType()));
			} else {
				json.put("packageType", JSONObject.NULL);
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public PTReport getEmptyEntity(){
		PTReport entity = new PTReport();
		return entity;
	}
}
